Page({
  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    content: "",
    contentLength: 0,
    type: "BUG",
    types: ["BUG", "功能建议", "体验问题", "其他"],
    phonenumber: "",
    deviceId: "",
    isEditing: false,
    feedbackId: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 判断是否是编辑模式
    if (options.edit && options.edit === "true" && options.feedback_id) {
      this.setData({
        isEditing: true,
        feedbackId: options.feedback_id,
      });
      // 获取反馈详情
      this.getFeedbackDetail(options.feedback_id);
    }

    // 获取用户联系方式
    const userInfo = wx.getStorageSync("userInfo");
    if (userInfo && userInfo.phone) {
      this.setData({
        phonenumber: userInfo.phone,
      });
    }

    // 获取用户设备ID
    if (userInfo && userInfo.deviceId) {
      this.setData({
        deviceId: userInfo.deviceId,
      });
    } else {
      this.getDeviceInfo();
    }
  },

  /**
   * 获取反馈详情
   */
  getFeedbackDetail: function (feedbackId) {
    const userInfo = wx.getStorageSync("userInfo");
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: "请先登录",
        icon: "none",
      });
      return;
    }

    // 确保feedbackId是字符串类型
    feedbackId = String(feedbackId);
    console.log("正在查找反馈ID:", feedbackId);

    wx.showLoading({
      title: "加载中...",
    });

    wx.request({
      url: "https://smartsound.top/api/feedback/v1/list",
      method: "GET",
      data: {
        user_id: userInfo.userId,
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data && res.data.code === 0 && res.data.feedback_list) {
          console.log("获取到反馈列表:", res.data.feedback_list);

          // 从返回的列表中查找对应ID的反馈，确保转换为字符串进行比较
          const feedback = res.data.feedback_list.find(
            (item) => String(item.feedback_id) === feedbackId
          );

          if (feedback) {
            console.log("找到匹配的反馈:", feedback);
            this.setData({
              title: feedback.title || "",
              content: feedback.content || "",
              contentLength: (feedback.content || "").length,
              type: feedback.type || "BUG",
              phonenumber: feedback.phonenumber || this.data.phonenumber,
            });
          } else {
            console.log("未找到匹配的反馈，已查找的ID:", feedbackId);
            console.log(
              "列表中的所有反馈ID:",
              res.data.feedback_list.map((item) => item.feedback_id)
            );
            wx.showToast({
              title: "未找到该反馈",
              icon: "none",
            });
          }
        } else {
          console.log("获取反馈列表失败:", res.data);
          wx.showToast({
            title: "获取反馈详情失败",
            icon: "none",
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error("获取反馈详情失败", err);
        wx.showToast({
          title: "网络错误，请稍后重试",
          icon: "none",
        });
      },
    });
  },

  /**
   * 获取设备信息
   */
  getDeviceInfo: function () {
    const app = getApp();
    const userInfo = wx.getStorageSync("userInfo");

    if (userInfo && userInfo.userId) {
      wx.request({
        url: `${app.globalData.apiBaseUrl}/api/v1/get_devices`,
        method: "GET",
        data: {
          user_id: userInfo.userId,
        },
        success: (res) => {
          if (
            res.data &&
            res.data.code === 0 &&
            res.data.devices &&
            res.data.devices.length > 0
          ) {
            this.setData({
              deviceId: res.data.devices[0].device_id,
            });
          }
        },
      });
    }
  },

  /**
   * 输入标题
   */
  inputTitle: function (e) {
    this.setData({
      title: e.detail.value,
    });
  },

  /**
   * 输入反馈内容
   */
  inputContent: function (e) {
    const content = e.detail.value;
    this.setData({
      content: content,
      contentLength: content.length,
    });
  },

  /**
   * 选择问题类型
   */
  selectType: function () {
    wx.showActionSheet({
      itemList: this.data.types,
      success: (res) => {
        this.setData({
          type: this.data.types[res.tapIndex],
        });
      },
    });
  },

  /**
   * 编辑联系方式
   */
  editPhonenumber: function () {
    wx.showModal({
      title: "联系方式",
      content: "请输入您的手机号码",
      editable: true,
      placeholderText: "请输入手机号码",
      success: (res) => {
        if (res.confirm && res.content) {
          this.setData({
            phonenumber: res.content,
          });
        }
      },
    });
  },

  /**
   * 提交反馈
   */
  submitFeedback: function () {
    if (!this.data.title.trim()) {
      wx.showToast({
        title: "请输入反馈标题",
        icon: "none",
      });
      return;
    }

    if (!this.data.content.trim()) {
      wx.showToast({
        title: "请输入反馈内容",
        icon: "none",
      });
      return;
    }

    wx.showLoading({
      title: this.data.isEditing ? "更新中..." : "提交中...",
      mask: true,
    });

    const userInfo = wx.getStorageSync("userInfo");
    const userId = userInfo ? userInfo.userId : "";

    // 统一使用submit接口，因为服务器尚未实现update接口
    const url = "https://smartsound.top/api/feedback/v1/submit";

    const data = {
      user_id: userId,
      title: this.data.title,
      content: this.data.content,
      type: this.data.type,
      phonenumber: this.data.phonenumber,
      device_id: this.data.deviceId,
    };

    // 如果是编辑模式，添加反馈ID
    if (this.data.isEditing) {
      data.feedback_id = this.data.feedbackId;
    }

    console.log("提交数据:", data);

    wx.request({
      url: url,
      method: "POST",
      data: data,
      success: (res) => {
        wx.hideLoading();
        console.log("提交响应:", res.data);
        if (res.data && res.data.code === 0) {
          wx.showToast({
            title: this.data.isEditing ? "反馈更新成功" : "反馈提交成功",
            icon: "success",
            duration: 2000,
            success: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 2000);
            },
          });
        } else {
          wx.showToast({
            title:
              res.data.message ||
              (this.data.isEditing ? "更新失败" : "提交失败"),
            icon: "none",
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error("请求失败:", err);
        wx.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      },
    });
  },

  /**
   * 返回上一页
   */
  navigateBack: function () {
    wx.navigateBack();
  },
});
